import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

//http://code.google.com/p/google-api-java-client/wiki/OAuth2

public class CopyOfDriveCommandLine {

  private static String CLIENT_ID = "572956856767-bvb7mbgqid98klnhov4oj11f1guikb44.apps.googleusercontent.com";
  private static String CLIENT_SECRET = "UCjHWkgebhNBfuppJE4jClMj";

  private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
  
  
  
  
  /** Global instance of the HTTP transport. */
  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  
  /** Authorizes the installed application to access user's protected data. 
   * <br> 这个方法取自
   * http://code.google.com/p/google-api-java-client/source/browse/plus-cmdline-sample/src/main/java/com/google/api/services/samples/plus/cmdline/PlusSample.java?repo=samples
   * */
  private static Credential authorize() throws Exception {
	  
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
        JSON_FACTORY, CopyOfDriveCommandLine.class.getResourceAsStream("/client_secrets.json"));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
        || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
      System.out.println(
          "Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
          + "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
      System.exit(1);
    }
    // set up file credential store
    java.io.File file=new  java.io.File(System.getProperty("user.home"),".credentials/drive.json");
    file.createNewFile();
    //file.mkdirs();
    
    FileCredentialStore credentialStore = new FileCredentialStore(
        new java.io.File(System.getProperty("user.home"), ".credentials/client_secrets.json"), JSON_FACTORY);
    //上述文件不能为空，必须已经包好有json的结构了，比如 {"credentials":{}}
    
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets,
        Arrays.asList(DriveScopes.DRIVE)).setCredentialStore(credentialStore).setAccessType("offline").setApprovalPrompt("auto").build();
    // authorize
    //这个user似乎仅仅是用来在json文件里保存本地的用户id的.
    //比如浏览器登录了账号a，你这里写的a1， 然后赋予权限了，则json中会保存名为a1的内容，里面写入了token
    //然后你浏览器换登录账号b，这里仍然写a1，运行程序，将会把文件保存在a账号下。
    //那么 如何让这里跟真实账号名字相同或者一一对应呢？
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("abcd");
    /*在以下链接中发现了解决方法：
http://code.google.com/p/google-api-java-client/source/browse/calendar-appengine-sample/src/main/java/com/google/api/services/samples/calendar/appengine/server/Utils.java?repo=samples
  //----  
  static Calendar loadCalendarClient() throws IOException {
    String userId = UserServiceFactory.getUserService().getCurrentUser().getUserId();
    Credential credential = newFlow().loadCredential(userId);
    return new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
  }
  //----
   * String userId = UserServiceFactory.getUserService().getCurrentUser().getUserId();
   * 分析以下:
   * 
   * 
    */
    
  }
  
  private static Credential authorize2() throws Exception {
	  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
			  HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
		        .setAccessType("offline")
		        .setApprovalPrompt("auto").build();

		    String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
		    System.out.println("Please open the following URL in your browser then type the authorization code:");
		    System.out.println("  " + url);
		    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		    String code = br.readLine();

		    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
		    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
		    return credential;
  }
  
  public static void main(String[] args) throws Exception {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    Credential credential =authorize();
    //Create a new authorized API client
    Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();

    //Insert a file
    File body = new File();
    body.setTitle("1My document");
    body.setDescription("A test document");
    body.setMimeType("text/plain");

    java.io.File fileContent = new java.io.File("pom.xml");
    FileContent mediaContent = new FileContent("text/plain", fileContent);

    File file = service.files().insert(body, mediaContent).execute();
    System.out.println("File ID: " + file.getId());
  }
}